const express = require('express')
var router = express.Router()
const memberService = require('../models/memberSerevice')
const userService = require('../models/userService')
const appcommonService = require('../models/appcommonService')
const ossService = require('../models/ossService')
const tradingService = require('../models/tradingService')
var reqData = require('../utils/reqData')

router.post('/login', function (req, res) {
  var datas = req.body
  datas.verifyCode = 'Ed%8r5'
  datas.clientIp = reqData.getClientIp(req) || '127.0.0.0'
  console.log(datas)
  memberService.login(datas, req).then(function (resp) {
    if (resp && resp.body && resp.body.token) {
      var domain = (req.hostname.indexOf('hairongyi.com') < 0) ? req.hostname : '.hairongyi.com'
      res.cookie('com.vfsso.cas.token', resp.body.token, {domain: domain})
      var datas = {
        token: resp.body.token
      }
      getUserInfoByToken(datas, req).then(function (userinfo) {
        if (userinfo.responseCode === 0) {
          if (req.headers.cookie && reqData.getResCookie(req.headers.cookie, 'openid')) {
            var datas = {userId: userinfo.userId,
              openId: reqData.getResCookie(req.headers.cookie, 'openid')}
            bindOpenIdAndUserId(datas, req).then(function (bindresult) {
              res.send(bindresult)
            }).catch(function (errors) {
              logger.error(errors)
              res.send({responseCode: 0})
            })
          } else {
            res.send(userinfo)
          }
        } else {
          res.send(errorInfo('type3'))
        }
      }).catch(function (errors) {
        logger.error(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp.body)
    }
  }).catch(function (errors) {
    logger.error(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/getrealname', function (req, res) {
  console.log('/api/getrealname')
  Promise.resolve(getUserId(req)).then(function (resp) {
    if (resp.responseCode === 0) {
      var datas = { userId: resp.userId }
      userService.getPersonalRealName(datas, req).then(function (result) {
        if (result && result.body && result.body.personalRealNameDto) {
          var outdata = { responseCode: 0, realName: result.body.personalRealNameDto.realName }
          res.send(outdata)
        } else {
          res.send(result.body)
        }
      }).catch(function (errors) {
        // console.log(errors)
        logger.error(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp)
    }
  }).catch(function (errors) {
    // console.log(errors)
    logger.error(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/getUserInvestInfo', function (req, res) {
  Promise.resolve(getUserId(req)).then(function (resp) {
    if (resp.responseCode === 0) {
      var datas = { userId: resp.userId }
      userService.getUserInvestInfo(datas, req).then(function (result) {
        res.send(result.body)
      }).catch(function (errors) {
        // console.log(errors)
        logger.error(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp)
    }
  }).catch(function (errors) {
    // console.log(errors)
    logger.error(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/getuserinvestdetail', function (req, res) {
  Promise.resolve(getUserId(req)).then(function (resp) {
    if (resp.responseCode === 0) {
      var datas = {
        hryId: resp.userId,
        curPage: 1,
        pageSize: 10,
        status: req.body.status
      }
      appcommonService.getuserInvestDetail(datas, req).then(function (result) {
        res.send(result.body)
      }).catch(function (errors) {
        // console.log(errors)
        logger.error(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp)
    }
  }).catch(function (errors) {
    // console.log(errors)
    logger.error(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/biddetail', function (req, res) {
  Promise.resolve(getUserId(req)).then(function (resp) {
    if (resp.responseCode === 0) {
      var datas = {
        hryId: resp.userId,
        recordId: req.body.recordId
      }
      appcommonService.getBidDetail(datas, req).then(function (result) {
        res.send(result.body)
      }).catch(function (errors) {
        // console.log(errors)
        logger.error(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp)
    }
  }).catch(function (errors) {
    // console.log(errors)
    logger.error(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/cfmatchlist', function (req, res) {
  const datas = req.body
  appcommonService.getMatchedBidList(datas, req).then(function (result) {
    res.send(result.body)
  }).catch(function (errors) {
    console.log(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/matchedbiddetail', function (req, res) {
  const datas = req.body
  appcommonService.getMatchedBidDetail(datas, req).then(function (result) {
    res.send(result.body)
  }).catch(function (errors) {
    console.log(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/getCouponAmount', function (req, res) {
  Promise.resolve(getUserId(req)).then(function (resp) {
    if (resp.responseCode === 0) {
      var datas = {
        hryId: resp.userId
      }
      ossService.getCouponAmount(datas, req).then(function (result) {
        res.send(result.body)
      }).catch(function (errors) {
        console.log(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp)
    }
  }).catch(function (errors) {
    console.log(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/queryCouponList', function (req, res) {
  Promise.resolve(getUserId(req)).then(function (resp) {
    if (resp.responseCode === 0) {
      var datas = req.body
      datas.hryId = resp.userId
      ossService.queryCouponList(datas, req).then(function (result) {
        res.send(result.body)
      }).catch(function (errors) {
        console.log(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp)
    }
  }).catch(function (errors) {
    console.log(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/getUserLcjDetail', function (req, res) {
  Promise.resolve(getUserId(req)).then(function (resp) {
    if (resp.responseCode === 0) {
      var datas = {
        hryId: resp.userId
      }
      ossService.getUserLcjDetail(datas, req).then(function (result) {
        res.send(result.body)
      }).catch(function (errors) {
        console.log(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp)
    }
  }).catch(function (errors) {
    console.log(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/queryLcjListByStatus', function (req, res) {
  Promise.resolve(getUserId(req)).then(function (resp) {
    if (resp.responseCode === 0) {
      var datas = req.body
      datas.hryId = resp.userId
      ossService.queryLcjListByStatus(datas, req).then(function (result) {
        res.send(result.body)
      }).catch(function (errors) {
        console.log(errors)
        res.send(errorInfo('type3'))
      })
    } else {
      res.send(resp)
    }
  }).catch(function (errors) {
    console.log(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/queryAllProductType', function (req, res) {
  tradingService.queryAllProductType({}, req).then(function (result) {
    res.send(result.body)
  }).catch(function (errors) {
    console.log(errors)
    res.send(errorInfo('type3'))
  })
})

router.post('/logout', function (req, res) {
  if (req.headers.cookie && reqData.getResCookie(req.headers.cookie, 'openid')) {
    var datas = {
      openId: reqData.getResCookie(req.headers.cookie, 'openid')
    }
    userService.unbindOpenIdAndUserId(datas, req).then(function (result) {
      res.send(result.body)
    }).catch(function (errors) {
      console.log(errors)
      res.send(errorInfo('type3'))
    })
  } else if (req.headers.cookie && reqData.getResCookie(req.headers.cookie, 'com.vfsso.cas.token')) {
    var datas = {
      token: reqData.getResCookie(req.headers.cookie, 'com.vfsso.cas.token')
    }
    userService.logout(datas, req).then(function (result) {
      res.send(result.body)
    }).catch(function (errors) {
      console.log(errors)
      res.send(errorInfo('type3'))
    })
  }
})

function errorInfo (type) {
  var result = {
    type1: {responseCode: -1, responseMessage: '系统繁忙，稍后再试'},
    type2: {responseCode: 5, responseMessage: '您还未登录，请先登录'},
    type3: {responseCode: 9999, responseMessage: '接口错误，请联系客服'}
  }

  return result[type]
}

function getUserInfoByToken (datas, req) {
  return userService.getUserIdBytoken(datas, req).then(function (resp) {
    if (resp && resp.body && resp.body.userDto && resp.body.userDto.userId) {
      return {responseCode: 0, userId: resp.body.userDto.userId}
    } else {
      return {responseCode: -1, responseMessage: '获取用户信息异常'}
    }
  }).catch(function (err) {
    console.log(err)
    return {responseCode: -1, responseMessage: '获取用户信息异常'}
  })
}

function bindOpenIdAndUserId (datas, req) {
  return userService.getUserIdAndBindOpenid(datas, req).then(function (resp) {
    if (resp && resp.body && resp.body.responseCode === 0) {
      return {responseCode: 0, userId: datas.userId}
    } else {
      return {responseCode: 0, userId: datas.userId, responseMessage: '绑定失败'}
    }
  }).catch(function (err) {
    console.log(err)
    return {responseCode: -1, userId: datas.userId, responseMessage: '绑定失败'}
  })
}

function getUserId (req) {
  console.log('api userid')
  console.log(req.body)
  var getCookieObj
  if (req.body && req.body.isServer) {
    getCookieObj = req.body.serverReqCookie
  } else {
    getCookieObj = req.headers.cookie
  }
  console.log(getCookieObj)
  if (getCookieObj && reqData.getResCookie(getCookieObj, 'openid')) {
    var datas = {
      openId: reqData.getResCookie(getCookieObj, 'openid')
    }
    return userService.getUserIdByOpenId(datas, req).then(function (res) {
      if (res && res.body) {
        return res.body
      } else {
        return errorInfo('type3')
      }
    }).catch(function (errors) {
      // console.log(errors)
      logger.error(errors)
      return errorInfo('type3')
    })
  } else if (getCookieObj && reqData.getResCookie(getCookieObj, 'com.vfsso.cas.token')) {
    var datas = {
      token: reqData.getResCookie(getCookieObj, 'com.vfsso.cas.token')
    }
    return userService.getUserIdBytoken(datas, req).then(function (resp) {
      if (resp && resp.body && resp.body.userDto && resp.body.userDto.userId) {
        return {responseCode: 0, userId: resp.body.userDto.userId}
      } else {
        return errorInfo('type2')
      }
    }).catch(function (err) {
      console.log(err)
      return errorInfo('type2')
    })
  } else {
    return errorInfo('type2')
    // return {responseCode: 0, userId: 10007952}
  }
}

module.exports = router
